#include "Scene/GameScene.h"
#include "AudioEngine.h"
#include "Other/Data.h"
#include "Scene/GameOverScene.h"
#include "Scene/GameVictorScene.h"
USING_NS_CC;
PlantVsZombies* plants_vs_zombies = new PlantVsZombies;
static int numofsum = 0; //存储阳光数量

Scene* GameScene::createScene() {
    return GameScene::create();
}

// on "init" you need to initialize your instance
bool GameScene::init() {
    if (!Scene::init()) {
        return false;
    }
    auto visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();
    AudioEngine::stopAll();
    //音乐播放
    AudioEngine::preload("Music/game.mp3");
    auto game_BGM = AudioEngine::play2d("Music/game.mp3", true);


    this->init_data();
    //鼠标 监听事件
    auto listener = EventListenerTouchOneByOne::create();
    listener->onTouchBegan = CC_CALLBACK_2(GameScene::onTouchBegan, this);
    listener->onTouchMoved = CC_CALLBACK_2(GameScene::onTouchMoved, this);
    listener->onTouchEnded = CC_CALLBACK_2(GameScene::onTouchEnded, this);
    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);

    //创建背景图 并且设置坐标为左起点
    auto background_sprite = Sprite::create("Games/bg1.jpg");
    background_sprite->setPosition(visibleSize.width / 2.0f + 150.0f, visibleSize.height / 2.0f);
    background_sprite->setScale(1.32f);
    this->addChild(background_sprite, 0);

    //// 卡片与阳光框 Sprite对象
    auto card_bar_sprite = Sprite::create("Games/ChooserBackground.png");
    card_bar_sprite->setPosition(Vec2(visibleSize.width / 2.0f - 153.0f, visibleSize.height / 2.0f + 130.0f));
    card_bar_sprite->setScale(1.3f);
    background_sprite->addChild(card_bar_sprite, 1);

    //覆盖初始阳光
    auto card_bar_sprite2 = Sprite::create("Games/sunNum.png");
    card_bar_sprite2->setPosition(Vec2(visibleSize.width / 2.0f - 315.0f, visibleSize.height / 2.0f + 110.0f));
    card_bar_sprite2->setScale(1.3f);
    background_sprite->addChild(card_bar_sprite2, 2);

    // 阳光数量
    sun_label = Label::createWithSystemFont(std::to_string(numofsum), "TypeFace/Marker Felt.ttf", 15);
    sun_label->setPosition(Vec2(visibleSize.width / 2.0f - 315.0f, visibleSize.height / 2.0f + 110.0f));
    background_sprite->addChild(sun_label, 3);
    sun_label->setColor(Color3B::BLACK);
    sun_label->setString(std::to_string(sun_total));   //用于动态修改阳光数量

    // 卡片槽 Menu对象
    // 铲子 Menu对象
   /* auto shovelMenu = MenuItemImage::create("Games/shovel.png", "Games/shovel.png", CC_CALLBACK_1(GameScene::menuCloseCallback, this));
    auto ShovelMenu = Menu::create(shovelMenu, NULL);
    ShovelMenu->setPosition(visibleSize.width * 0.63f, visibleSize.height * 0.92f);
    this->addChild(ShovelMenu, 1);*/
    // 确认 Menu对象

    //场景绑定
    plants_vs_zombies->init_scene(this);
    this->addChild(plants_vs_zombies);

    //汽车创建
    for (int i = 0; i < 5; i++) {
        Car* temp_car = new Car;
        temp_car->sprite_init(Vec2(car_positon[i]));
        temp_car->sprite->setScale(1.8f);
        plants_vs_zombies->addChild(temp_car->sprite);
        temp_car->row = i; //设置为第n行
        car_date.push_back(temp_car);
    }


    SunFlowerCard* card1 = new SunFlowerCard;    //sunflower card
    card1->sprite_init("SunFlower", Vec2(135, 555));
    this->addChild(card1->sprite, 2);
    card_date.push_back(card1);
    PeashooterCard* card2 = new PeashooterCard;   //peashooter card
    card2->sprite_init("PeaShooter", Vec2(185, 555));
    this->addChild(card2->sprite, 2);
    card_date.push_back(card2);
    WallNutCard* card3 = new WallNutCard;     //wallnut card
    card3->sprite_init("WallNut", Vec2(235, 555));
    this->addChild(card3->sprite, 2);
    card_date.push_back(card3);


    auto sp1 = Sprite::create("Games/loading/timerBar2.png");
    auto sp3 = Sprite::create("Games/loading/FlagMeterLevelProgress.png");
    auto load_bar = ProgressTimer::create(Sprite::create("Games/loading/timerBar1.png")); // 加入进度条精灵
    sp1->setScale(2);
    sp3->setScale(2);
    load_bar->setScale(2);
    sp3->setPosition(Vec2(800, 30));
    //三个默认设置 一般不改
    load_bar->setType(ProgressTimer::Type::BAR); //方向
    load_bar->setBarChangeRate(Vec2(1, 0));
    load_bar->setMidpoint(Vec2(0, 0));
    load_bar->runAction(ProgressFromTo::create(120, 0, 100)); // 时间  起点百分百   终点百分比
    load_bar->setPosition(Vec2(800, 15));
    sp1->setPosition(Vec2(800, 15));
    this->addChild(load_bar, 3);
    this->addChild(sp1, 2);
    this->addChild(sp3, 2);
    plants_vs_zombies->create_sun(300, 300);

    /*auto sp_g1 = Sprite::create("Games/loading/LargeWave.png");
    auto sp_g2 = Sprite::create("Games/loading/FinalWave.png");
    sp_g1->setPosition(visibleSize.width / 2, visibleSize.height / 2);
    sp_g2->setPosition(visibleSize.width / 2, visibleSize.height / 2);
    sp_g1->setScale(4);
    sp_g1->setVisible(false);
    this->addChild(sp_g1 , 4);
    sp_g2->setScale(2);
    sp_g1->setVisible(false);
    this->addChild(sp_g2, 4);*/

    this->scheduleUpdate();
    return true;
}

void GameScene::init_data() { 
    auto visibleSize = Director::getInstance()->getVisibleSize();
    //坐标初始化 
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 9; j++) {
            float ii = 0.15f * i + 0.15f, jj = 0.21f + j * 0.09f;
            plant_position[i][j] = Vec2(visibleSize.width * jj, visibleSize.height * ii);
        }
    }
    //僵尸坐标初始  下标代表row   保证起点不同  出发的时间不同
    zombie_positon[0] = Vec2(1400, visibleSize.height * (0.15f));
    zombie_positon[1] = Vec2(1300, visibleSize.height * (0.15f * 1 + 0.17f));
    zombie_positon[2] = Vec2(1000, visibleSize.height * (0.15f * 2 + 0.17f));
    zombie_positon[3] = Vec2(1000, visibleSize.height * (0.15f * 3 + 0.20f));
    zombie_positon[4] = Vec2(1200, visibleSize.height * (0.15f * 4 + 0.20f));
    car_positon[0] = Vec2(visibleSize.width * 0.12f, visibleSize.height * (0.15f));
    car_positon[1] = Vec2(visibleSize.width * 0.12f, visibleSize.height * (0.15f * 1 + 0.17f));
    car_positon[2] = Vec2(visibleSize.width * 0.12f, visibleSize.height * (0.15f * 2 + 0.17f));
    car_positon[3] = Vec2(visibleSize.width * 0.12f, visibleSize.height * (0.15f * 3 + 0.20f));
    car_positon[4] = Vec2(visibleSize.width * 0.12f, visibleSize.height * (0.15f * 4 + 0.20f));
}

bool bg1 = false, bg2 = false;

void GameScene::update(float update_time) {
    
    if (plants_vs_zombies->is_pass_time2 && !bg1) {
        auto visibleSize = Director::getInstance()->getVisibleSize();
        Vec2 origin = Director::getInstance()->getVisibleOrigin();
        bg1 = true;
       /* auto sp_g1 = Sprite::create("Games/loading/LargeWave.png");
        sp_g1->setPosition(visibleSize.width / 2, visibleSize.height / 2);
        sp_g1->setScale(4);
        sp_g1->setOpacity(254);
        this->addChild(sp_g1, 4);
        auto fadeOut = FadeOut::create(1.0f);
        sp_g1->runAction(Sequence::create(DelayTime::create(2),RemoveSelf::create()));*/

        auto game_BGM = AudioEngine::play2d("Music/finalwave.ogg", false);
    }

    if (plants_vs_zombies->is_pass_time3 && !bg2 ) {
        auto visibleSize = Director::getInstance()->getVisibleSize();
        bg2 = true;

        auto game_BGM = AudioEngine::play2d("Music/awooga.ogg", false);
       /* auto sp_g2 = Sprite::create("Games/loading/FinalWave.png");
        sp_g2->setPosition(visibleSize.width / 2, visibleSize.height / 2);
        sp_g2->setScale(2);
        this->addChild(sp_g2, 4);*/
    }

    for (auto& it : card_date) {
        if (it->judge_cd()) { // 如果在cd状态
            it->time_count += update_time;
            if (it->card_cd <= it->time_count) {
                it->set_is_cd(false);
                it->time_count = 0.0;
            }
        }
    }

    if (plants_vs_zombies->is_game_fail == true) { // 判断游戏失败
        zombie_date.clear();
        plant_date.clear();
        bullet_date.clear();
        card_date.clear();
        car_date.clear();
        sun_date.clear();
        for (auto& it : plant_judge_position)
        {
            for (auto& elem : it)
            {
                elem = false;
            }
        }
        //delete plants_vs_zombies;
        sun_total = 50;
        Director::getInstance()->replaceScene(GameOverScene::create());
        plants_vs_zombies = new PlantVsZombies();
    }
    if (plants_vs_zombies->is_game_success == true) { // 判断游戏胜利
        zombie_date.clear();
        plant_date.clear();
        bullet_date.clear();
        card_date.clear();
        car_date.clear();
        sun_date.clear();
        for (auto& it : plant_judge_position)
        {
            for (auto& elem : it)
            {
                elem = false;
            }
        }
        sun_total = 50;
        Director::getInstance()->replaceScene(GameVictorScene::create());
        plants_vs_zombies = new PlantVsZombies();
    }

}

void GameScene::menuCloseCallback(Ref* pSender) {
    Director::getInstance()->end();
}

bool GameScene::onTouchBegan(Touch* touch, Event* unused_event) {
    auto touch_position = touch->getLocation();
    for (auto& it : sun_date) {//这里查看鼠标点击位置是否有阳光
        if (it->judge_delete())	continue;
        double width_ = it->sprite->getContentSize().width / 2;
        double height_ = it->sprite->getContentSize().height / 2;
        Vec2 SunPosition_ = it->sprite->getPosition();
        auto offset_ = SunPosition_ - touch_position;
        if ((fabs(offset_.x) <= width_) && (fabs(offset_.y) <= height_)) {  //说明鼠标点击位置是阳光所在位置
            sun_total += 50;
            it->run_sun_collect_animation();
            this->sun_label->setString(to_string(sun_total));
            return true;
        }
    }

    //这里查看鼠标点击的位置是不是植物卡片的位置
    for (auto& it : card_date) {
        if (it->judge_cd() || mouse_sprite != nullptr) continue;
        double width_ = it->sprite->getContentSize().width / 2;
        double height_ = it->sprite->getContentSize().height / 2;
        Vec2 card_positon = it->sprite->getPosition();
        auto offset_ = card_positon - touch_position;
        if ((fabs(offset_.x) <= width_) && (fabs(offset_.y) <= height_)) {
            switch (it->card_type) {
            case CardType::card_type_Peashooter:
            {
                Peashooter* pe = new Peashooter;
                mouse_sprite = pe->run_plant_animation(it->sprite->getPosition());
                this->addChild(mouse_sprite, 1);
                selete_plant_type = PlantType::Peashooter;
                break;
            }
            case CardType::card_type_SunFlower:
            {
                SunFlower* pe = new SunFlower;
                mouse_sprite = pe->run_plant_animation(it->sprite->getPosition());
                this->addChild(mouse_sprite, 1);
                selete_plant_type = PlantType::SunFlower;
                break;
            }
            case CardType::card_type_WallNut:
            {
                WallNut* pe = new WallNut;
                mouse_sprite = pe->run_plant_animation(it->sprite->getPosition());
                this->addChild(mouse_sprite, 1);
                selete_plant_type = PlantType::WallNut;
                break;
            }
            default: {
                break;
            }
            }
            return true;
        }
    }
    return false;
}

void GameScene::onTouchMoved(Touch* touch, Event* unused_event) {
    if (mouse_sprite != nullptr && selete_plant_type != PlantType::plant_type_none) {
        int row_, col_;
        mouse_sprite->setPosition(touch->getLocation());
        if (plants_vs_zombies->judge_vec2_in_row_col(touch->getLocation(), row_, col_)) { //判断鼠标是否在草地区域
            if (plant_judge_position[row_][col_] == false)	mouse_sprite->setPosition(plant_position[row_][col_]);
            else {
                mouse_sprite->setPosition(touch->getLocation());
            }
        }
        else {
            mouse_sprite->setPosition(touch->getLocation());
        }
    }
}


void GameScene::onTouchEnded(Touch* touch, Event* unused_event) {
    if (mouse_sprite != nullptr && selete_plant_type != PlantType::plant_type_none) {
        int row_, col_;
        if (plants_vs_zombies->judge_vec2_in_row_col(touch->getLocation(), row_, col_)) {//鼠标位置在坑中 
            if (plants_vs_zombies->judge_plant(row_, col_) == false) {
                plant_down(row_, col_, selete_plant_type);
            }
        }
        selete_plant_type = PlantType::plant_type_none;
    }
    this->removeChild(mouse_sprite);
    mouse_sprite = nullptr;
}

//种植 + 判断
void GameScene::plant_down(int row_, int col_, PlantType plant_type_) {
    if (plant_judge_position[row_][col_] == true)	return;

    //根据类型  获取卡片对象
    Card* temp_card = nullptr;
    int idx = -1;
    switch (plant_type_) {
    case PlantType::SunFlower:
    {
        temp_card = card_date[0];  // 太阳花卡片
        idx = 0;
        break;
    }
    case PlantType::Peashooter:
    {
        temp_card = card_date[1]; // 豌豆卡片
        idx = 1;
        break;
    }
    case PlantType::WallNut:
    {
        temp_card = card_date[2]; // 坚果卡片
        idx = 2;
        break;
    }
    default:
        break;
    }
    if (!temp_card->judge_cd()) { //不在冷却时间
        //判断当前的阳光是否足够种植该植物
        if (sun_total >= temp_card->sun_cost) { //阳光足够
            sun_total -= temp_card->sun_cost;
            this->sun_label->setString(to_string(sun_total));
            card_date[idx]->set_is_cd(true); // 设置卡片为cd状态
            card_date[idx]->init_card_cd_animation();
            plant(row_, col_, plant_type_);
            AudioEngine::play2d("Music/plant2.ogg", false);
            return;
        }
    }
    //plant(row_, col_, plant_type_);
}

void GameScene::plant(int row_, int col_, PlantType plant_type) {
    if (plant_judge_position[row_][col_])
    {
        return;
    }
    plant_judge_position[row_][col_] = true;
    //float cow_to_x[9] = { 0.21 , 0.30 , 0.39 , 0.49 , 0.58 , 0.67 , 0.755 , 0.84 , 0.94 };
    //float row_to_y[5] = { 0.15 , 0.30 , 0.46 , 0.63 , 0.79 };
    //int x_position = Director::getInstance()->getVisibleSize().width * cow_to_x[col_];
    //int y_position = Director::getInstance()->getVisibleSize().height * row_to_y[row_];
    Plant* temp_push = NULL;
    switch (plant_type)
    {
    case PlantType::SunFlower:
        temp_push = new SunFlower();
        this->addChild(temp_push->run_plant_animation(plant_position[row_][col_]));
        temp_push->set_plant_type(PlantType::SunFlower);
        break;
    case PlantType::WallNut:
        temp_push = new WallNut();
        this->addChild(temp_push->run_plant_animation(plant_position[row_][col_]));
        temp_push->set_plant_type(PlantType::WallNut);
        break;
    case PlantType::Peashooter:
        temp_push = new Peashooter();
        this->addChild(temp_push->run_plant_animation(plant_position[row_][col_]));
        temp_push->set_plant_type(PlantType::Peashooter);
        break;
    default:
        break;
    }
    plant_date.emplace_back(temp_push);
}


int row_plant_cnt(int row_) {
    int cnt = 0;
    for (auto& it : plant_date) {
        if (it->get_row() != row_) continue;
        else cnt++;
    }
    return cnt;
} // 获取这一路的植物数量。
